<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\Authenticate;

class JWTAuthenticate extends Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $this->authenticate($request);

            return $next($request);
        } catch (UnauthorizedHttpException $e) {
            try {
                $token = $this->auth->refresh();
                $userId = $this
                    ->auth
                    ->manager()
                    ->getPayloadFactory()
                    ->buildClaimsCollection()
                    ->toPlainArray()['sub'];

                if (!auth('api')->onceUsingId($userId)) {
                    throw new UnauthorizedHttpException('jwt-auth', $e->getMessage());
                }
            } catch (JWTException $e) {
                throw new UnauthorizedHttpException('jwt-auth', $e->getMessage());
            }
        }

        $response = $next($request);

        return $this->setAuthenticationHeader($response, $token);
    }
}
